package com.ezops.poc.aggregation;

import java.util.ArrayList;
import java.util.List;

import org.apache.camel.Exchange;
import org.apache.camel.processor.aggregate.AggregationStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EzopsAggregationStrategy implements AggregationStrategy {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(EzopsAggregationStrategy.class);

	@Override
	public Exchange aggregate(Exchange exchange, Exchange exchange2) {

		if (exchange == null) {
			return exchange2;
		}

		LOGGER.debug("\n Old Exchage Order: "
				+ exchange.getIn().getBody(String.class));
		LOGGER.debug("\n New Exchnge Order: "
				+ exchange2.getIn().getBody(String.class));

		if (exchange.getIn().getBody() instanceof List) {

			final List convertedTrades = exchange.getIn().getBody(List.class);
			convertedTrades.add(exchange2.getIn().getBody());
			exchange.getIn().setBody(convertedTrades);
		} else {
			final List convertedTrades = new ArrayList<>();
			convertedTrades.add(exchange2.getIn().getBody());
			convertedTrades.add(exchange.getIn().getBody());
			exchange.getIn().setBody(convertedTrades);

		}

		return exchange;
	}
}
